package com.vote.admin.service;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.vote.admin.vo.param.SwitchParam;
import com.vote.admin.vo.result.UserResult;
import com.vote.admin.vo.result.ViewResult;
import com.vote.common.entity.VoteProject;
import com.vote.common.entity.VoteUser;
import com.vote.common.returns.RespCode;
import com.vote.common.returns.RespEntity;
import com.vote.common.returns.RespTable;
import com.vote.common.service.VoteProjectService;
import com.vote.common.service.VoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class AdminUserService {

    @Autowired
    private VoteUserService voteUserService;

    /**
     * 用户列表
     * @param page
     * @param limit
     * @param column
     * @param value
     * @return
     */
    public RespTable<List<UserResult>> userList(Integer page, Integer limit, String column, String value) {
        QueryWrapper<VoteUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(VoteUser::getType, 0, 1)
                .eq(VoteUser::getDeleted, 0);

        //多条件模糊查询
        if (StringUtils.isNotBlank(column)) {
            queryWrapper.like(column, value);
        }

        //分页逻辑
        IPage<VoteUser> iPage = new Page<>(page, limit);
        IPage<VoteUser> pg = voteUserService.page(iPage, queryWrapper);

        //数据组装
        List<VoteUser> records = pg.getRecords();
        List<UserResult> userResultList = Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(records)) {
            for (VoteUser record : records) {
                UserResult userResult = UserResult.builder()
                        .id(record.getId())
                        .username(record.getUsername())
                        .name(record.getName())
                        .type(record.getType())
                        .build();

                userResultList.add(userResult);
            }
        }

        return new RespTable<>(RespCode.OK, userResultList, pg.getTotal());
    }

    /**
     * 编辑用户类别
     * @param switchParam
     * @return
     */
    public RespEntity updateSwitch(SwitchParam switchParam) {

        VoteUser voteUser = VoteUser.builder()
                .id(switchParam.getId())
                .type(switchParam.getType())
                .build();
        voteUserService.updateById(voteUser);

        return new RespEntity(RespCode.SUCCESS);
    }
}
